#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@File    ：mail.py
@IDE     ：PyCharm
@Author  ：yy
@Date    ：2025/5/16 17:45
'''
import pandas as pd
import akshare as ak
from datetime import datetime
import numpy as np
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime

def fetch_finance_data():
    """获取并预处理财经数据"""
    # 获取原始数据
    global_news = ak.stock_info_global_em()
    cjzc_news = ak.stock_info_cjzc_em()
    # stock_cyq_em_df = ak.stock_cyq_em(symbol="000001", adjust="")  # 东方财富网-概念板-行情中心-日K-筹码分布  可用
    # stock_research_report_em_df = ak.stock_research_report_em(symbol="000001") # 东方财富网-研究报告-研究报告数据-个股研报  可用
    stock_institute_recommend_df = ak.stock_institute_recommend(symbol="最新投资评级") # 东方财富网-机构推荐-最新投资评级  可用
    stock_hsgt_fund_flow_summary_em_df = ak.stock_hsgt_fund_flow_summary_em()  # 单次获取沪深港通资金流向数据 可用
    return global_news, cjzc_news,stock_institute_recommend_df,stock_hsgt_fund_flow_summary_em_df





class DataFrameMailer:
    def __init__(self, df):
        self.df = df.copy()
        self._preprocess_data()

    def _preprocess_data(self):
        """数据预处理：类型推断与格式标准化"""
        # 自动日期识别
        date_cols = [col for col in self.df.columns
                     if pd.api.types.is_datetime64_any_dtype(self.df[col])]
        for col in date_cols:
            self.df[col] = self.df[col].dt.strftime('%Y-%m-%d')

        # 数值类型处理
        num_cols = self.df.select_dtypes(include=np.number).columns
        self.df[num_cols] = self.df[num_cols].applymap(
            lambda x: f"{x:,.2f}" if isinstance(x, (int, float)) else x
        )

        # 文本截断（防止HTML破坏）
        str_cols = self.df.select_dtypes(include='object').columns
        self.df[str_cols] = self.df[str_cols].applymap(
            lambda x: str(x)[:50] + '...' if len(str(x)) > 50 else x
        )

    def _generate_dynamic_styles(self):
        """生成响应式CSS样式"""
        num_cols = len(self.df.columns)
        col_width = min(120, 1200 // max(num_cols, 1))

        return f"""
        <style>
        .auto-table {{
            width: {col_width * num_cols}px;
            border-collapse: collapse;
            margin: 20px 0;
            font-family: 'Segoe UI', Arial, sans-serif;
        }}
        .auto-table th {{
            background-color: #2c3e50;
            color: white;
            padding: 12px;
            text-align: left;
            position: sticky;
            top: 0;
        }}
        .auto-table td {{
            padding: 8px;
            border: 1px solid #ddd;
            max-width: 300px;
            word-wrap: break-word;
            vertical-align: top;
        }}
        .numeric {{ text-align: right !important; }}
        .missing {{ color: #e74c3c; font-style: italic; }}
        @media screen and (max-width: 600px) {{
            .auto-table {{ width: 100% !important; }}
        }}
        </style>
        """

    def _generate_html_table(self):
        """生成自适应HTML表格"""
        # 动态列类型标记
        type_mapper = {
            'object': '',
            'datetime': '',
            'number': 'numeric'
        }

        html = self.df.to_html(
            index=False,
            escape=False,
            classes='auto-table',
            na_rep='<span class="missing">N/A</span>'
        )

        # 添加列类型样式
        for col in self.df.columns:
            col_type = pd.api.types.infer_dtype(self.df[col])
            html = html.replace(
                f'<th>{col}</th>',
                f'<th>{col}<br><small>{col_type}</small></th>'
            )
            if col_type in ['integer', 'floating']:
                html = html.replace(f'<td>{col}', f'<td class="{type_mapper[col_type]}">{col}')

        return html

    def send_mail(self, config):
        """执行邮件发送"""
        # 构造邮件内容
        msg = MIMEMultipart()
        msg['From'] = config['sender']
        msg['To'] = ', '.join(config['recipients'])
        msg['Subject'] = f"Data Report - {datetime.now().strftime('%Y%m%d')}"

        full_html = f"""
        <html>
          <head>{self._generate_dynamic_styles()}</head>
          <body>
            <h2 style="color: #34495e;">动态数据报告</h2>
            <p>生成时间：{datetime.now().strftime('%Y-%m-%d %H:%M')}</p>
            {self._generate_html_table()}
            <div style="margin-top: 20px; color: #95a5a6;">
              数据概要：共 {len(self.df)} 行 × {len(self.df.columns)} 列
            </div>
          </body>
        </html>
        """

        msg.attach(MIMEText(full_html, 'html'))

        # 发送邮件
        with smtplib.SMTP_SSL(config['smtp_host'], config['smtp_port']) as server:
            server.login(config['user'], config['password'])
            server.send_message(msg)


# 使用示例
if __name__ == "__main__":
    # 生成测试数据

    df1,df2,df3,df4 =fetch_finance_data()
    # 配置邮件参数
    mail_config = {
        'smtp_host': 'smtp.qq.com',
        'smtp_port': 465,
        'user': '1090157332@qq.com',
        'password': '',
        'sender': '1090157332@qq.com',
        'recipients': ['858626404@qq.com']
    }

    # 执行发送
    # mailer = DataFrameMailer(df1)
    # mailer.send_mail(mail_config)

    mailer = DataFrameMailer(df2)
    mailer.send_mail(mail_config)

    mailer = DataFrameMailer(df3)
    mailer.send_mail(mail_config)

    mailer = DataFrameMailer(df4)
    mailer.send_mail(mail_config)